package com.mingliqiye.minecraft.enchantment.conflict.common.enchantment;

import com.mingliqiye.minecraft.enchantment.conflict.common.ConfigManager;
import com.mingliqiye.minecraft.enchantment.conflict.common.ConfigPair;
import java.util.ArrayList;
import java.util.List;

public class EnchantmentController {

    private final List<AddAllowEnchantmentFunInf> allowEnchantmentFunInfs = new ArrayList<>();
    private final ConfigManager configManager;

    public void registerAllowEnchantment(AddAllowEnchantmentFunInf fun) {
        allowEnchantmentFunInfs.add(fun);
    }

    public EnchantmentController(ConfigManager configManager) {
        this.configManager = configManager;
    }

    public Boolean canBeCombined(String enchantmentA, String enchantmentB) {
        if (enchantmentA.equals(enchantmentB)) {
            return true;
        }
        List<EnchantmentEntity> groupsA = ofId(enchantmentA);
        List<EnchantmentEntity> groupsB = ofId(enchantmentB);
        if (groupsA.isEmpty() && groupsB.isEmpty()) {
            return null;
        }

        for (EnchantmentEntity groupA : groupsA) {
            for (EnchantmentEntity groupB : groupsB) {
                if (groupA.getFather().equals(groupB.getFather())) {
                    ConfigPair pair = configManager.getConfig().get(groupA.getFather());
                    if (pair == null) {
                        return null;
                    }
                    return pair.getAllow();
                }
            }
        }
        return null;
    }

    public List<EnchantmentEntity> ofId(String id) {
        final List<EnchantmentEntity> enchantmentList = new ArrayList<>();
        for (String i : configManager.getConfig().keySet()) {
            if (configManager.getConfig().get(i).getAllowlist().contains(id)) {
                enchantmentList.add(new EnchantmentEntity(id, i, "", null));
            }
        }
        return enchantmentList;
    }
}
